<template>
    <div>
        <div>
            <el-breadcrumb separator-class="el-icon-arrow-right">
                <el-breadcrumb-item :to="{ path: backHomeStart+'EchartsList' }">首页</el-breadcrumb-item>
                <el-breadcrumb-item>用户中心</el-breadcrumb-item>
                <el-breadcrumb-item :to="{ path: backHomeStart+'UserList' }">用户列表</el-breadcrumb-item>
                <el-breadcrumb-item :to="{ path: backHomeStart+'AddUser' }">新建用户</el-breadcrumb-item>
            </el-breadcrumb>
        </div>
        <el-divider></el-divider>
        <div class="contentSize">
            <div class="addUder">
                <h3>新建用户</h3>
                <el-form :model="ruleForm" status-icon :rules="rules"  ref="ruleForm" label-width="120px" class="demo-ruleForm">
                    <div :span="15" class="floatLeft">
                        <el-form-item label="用户名字" prop="uUsername">
                            <el-input v-model="ruleForm.uUsername"></el-input>
                        </el-form-item>
                        <el-form-item label="用户性别" prop="uSex" class="borderSize">
                            <el-select v-model="ruleForm.uSex" placeholder="请选择性别">
                                <div v-for="sex in sexs">
                                    <el-option :label="sex" :value="sex"></el-option>
                                </div>
                            </el-select>
                        </el-form-item>

                        <el-form-item label="真实姓名" prop="uRealname">
                            <el-input v-model="ruleForm.uRealname"></el-input>
                        </el-form-item>
                        <el-form-item label="生日日期" prop="uBirthday">
                            <el-col :span="12">
                                <el-date-picker type="date" placeholder="选择生日日期" v-model="ruleForm.uBirthday"></el-date-picker>
                            </el-col>
                        </el-form-item>
                        <el-form-item label="邮箱账号" prop="uEmail">
                            <el-input v-model="ruleForm.uEmail"></el-input>
                        </el-form-item>
                        <el-form-item label="手机号码" prop="uPhone">
                            <el-input v-model="ruleForm.uPhone"></el-input>
                        </el-form-item>
                        <el-form-item label="账号密码" prop="uPassword">
                            <el-input type="password" v-model="ruleForm.uPassword" autocomplete="off"></el-input>
                        </el-form-item>

                        <el-form-item label="居住城市" prop="uCity">
                            <el-select v-model="ruleForm.uCity" placeholder="请选择上架状态">
                                <div v-for="(city) in citys">
                                    <el-option :label="city" :value="city"></el-option>
                                </div>
                            </el-select>
                        </el-form-item>
                        <el-form-item label="详细地址" prop="uAddress">
                            <el-input v-model="ruleForm.uAddress"></el-input>
                        </el-form-item>
                        <el-form-item>
                            <el-button type="primary" @click="submitForm('ruleForm')">新建</el-button>
                            <el-button @click="resetForm('ruleForm')">重置</el-button>
                            <el-button @click="goBack">返回</el-button>
                        </el-form-item>
                    </div>
                    <div class="floatRight">
                        <el-tag class="headerSize">用户头像</el-tag>
                        <el-upload
                                class="avatar-uploader"
                                action="String"
                                ref="upload"
                                :show-file-list="false"
                                :on-change="handleAvatarSuccess"
                                :http-request="uploadFile"
                                :auto-upload="false"
                        >
                            <img v-if="dialogImageUrl" :src="dialogImageUrl" class="avatar">
                            <i v-else class="el-icon-plus avatar-uploader-icon"></i>
                        </el-upload>
                    </div>
                </el-form>
            </div>
        </div>
    </div>
</template>

<script>
    import Avatar from "../../components/Avatar";
    import HeadPhotoUpload from "../../components/HeadPhotoUpload";
    export default {
        name: "AddUser",
        data() {
            return {
                sexs:['男士','女士'],
                citys:['上海','成都','广州','北京'],
                dialogImageUrl: '',
                backHomeStart:this.$store.state.backHomeHeader,
                ruleForm: {
                    uUsername: '',
                    uSex: '',
                    uRealname: '',
                    uBirthday: '',
                    uEmail: '',
                    uPhone: '',
                    uPassword: '',
                    uCity: '',
                    uAddress: '',
                    uCreatedate: '',
                    userHeaderPic:null,

                },
                /*验证规则*/
                rules: {
                    uUsername: [
                        { required: true, message: '请输入昵称:', trigger: 'blur' },
                        { min: 1, max: 10, message: '长度在 1 到 10 个字符', trigger: ['blur', 'change'] }
                    ],
                    uSex: [
                        { required: true, message: '请选择性别', trigger: 'change' }
                    ],
                    uRealname: [
                        { required: true, message: '请输入真实姓名:', trigger: ['blur', 'change'] },
                        { min: 2, max: 16, message: '长度在 2 到 16 个字符', trigger: ['blur', 'change'] }
                    ],
                    uBirthday: [
                        { required: true, message: '请选择日期', trigger: ['change'] }
                    ],
                    uEmail: [
                        { required: true, message: '请输入邮箱地址:', trigger: ['blur', 'change'] },
                        { type: 'email', message: '请输入正确的邮箱地址', trigger: ['blur', 'change'] }
                    ],
                    uPhone: [
                        { required: true, message: '请输入手机号码:', trigger: ['blur', 'change'] },
                        { min: 13, max: 15, message: '长度在 13 到 15 个字符', trigger: ['blur', 'change'] }
                    ],
                    uPassword: [
                        { required: true, message: '请输入初始密码:', trigger: ['blur', 'change'] },
                        { min: 13, max: 15, message: '长度在 13 到 15 个字符', trigger: ['blur', 'change'] }
                    ],
                    uCity: [
                        { required: true, message: '请选择城市', trigger: ['blur', 'change'] }
                    ],
                    uAddress: [
                        { required: true, message: '请输入详情地址', trigger: ['blur', 'change'] },
                        { min: 0, max: 50, message: '长度在 0 到 50 个字符', trigger: ['blur', 'change'] }
                    ]
                }
            };
        },
        methods: {
            saveGoods(user){
                this.$axios.post("/user/insert",user,{headers:{'content-type':'multipart/form-data;charset=utf-8'}}
                ).then(reulst=>{
                    this.addResult(reulst.data);
                    this.$router.push("/BackHome/UserList");
                }).catch(err=>{
                    alert(err);
                })
            },
            changToFormData(user){
                const form = new FormData();
                form.append("uUsername",user.uUsername);
                form.append("uSex",user.uSex);
                form.append("uRealname",user.uRealname);
                form.append("uBirthday",user.uBirthday);
                form.append("uEmail",user.uEmail);
                form.append("uPhone",user.uPhone);
                form.append("uPassword",user.uPassword);
                form.append("uCity",user.uCity);
                form.append("uAddress",user.uAddress);
                form.append("uCreatedate",user.uCreatedate);
                form.append("userHeaderPic",user.userHeaderPic);
                return form;
            },
            getCurrenTime(){
                var now = new Date();
                let time = now.getTime();
                let date = this.$moment(time).format('YYYY-MM-DD HH:mm:ss');
                this.ruleForm.uCreatedate = date;
            },
            submitForm(formName) {
                this.$refs[formName].validate((valid) => {
                    if (valid) {
                        this.$refs.upload.submit();
                        this.getCurrenTime();
                        let birthday = this.$moment(this.ruleForm.uBirthday).format('YYYY-MM-DD');
                        this.ruleForm.uBirthday = birthday;
                        console.log(this.ruleForm);
                        let formData = this.changToFormData(this.ruleForm);
                        console.log(formData);
                        this.saveGoods(formData);
                    } else {
                        console.log('数据有误!!');
                        return false;
                    }

                });
            },
            resetForm(formName) {
                this.$refs[formName].resetFields();
            },
            addResult(val) {
                this.$message({
                    showClose: true,
                    message: val===true?'恭喜你，添加成功！':'错了哦，添加失败！',
                    type: val===true?'success':'error'
                });
            },
            goBack(){
                this.$router.push("/BackHome/UserList")
            },
            handleAvatarSuccess(file) {
                this.dialogImageUrl =URL.createObjectURL(file.raw);

            },
            uploadFile(file){
               this.ruleForm.userHeaderPic=file.file;
            },
            beforeAvatarUpload(file) {
                const isJPG = /^image\/(jpeg|png|jqp|gif)$/.test(file.type)
                const isLt2M = file.size / 1024 / 1024 < 5;
                if (!isJPG) {
                    this.$message.error('上传头像图片只能是 image/jpeg/bmp/jpg/png/gif 格式!');
                }
                if (!isLt2M) {
                    this.$message.error('上传头像图片大小不能超过 5MB!');
                }
                return isJPG && isLt2M;
            }
        },
        components:{
            Avatar,
            HeadPhotoUpload
        }
    }
</script>

<style scoped>
    .contentSize{
        padding: 20px;
              /*height: 680px;*/
        /*!*border: 1px solid red;*!*/
        /*box-shadow: 0 2px 12px 0 rgba(0, 0, 0, 0.1);*/
        /*width: 880px;*/
        /*margin: 0 auto;*/

    }
    .addUder{
        box-shadow: 0 1px 5px 0 rgba(0, 0, 0, 0.1);
        border: 1px solid rgba(0, 0, 0, 0.1);
        padding: 20px;
        width: 880px;
        height: 680px;
        border-radius: 5px;

    }
    .floatRight{
        float: right;
        /*border: 1px #8affb7 solid;*/
    }
    .floatLeft{
        float: left;
        /*border: 1px red solid;*/
    }
    .el-input{
        max-width: 680px;
    }
    .borderSize{

    }
    .el-button{
        margin-left: 30px;
    }
    .el-date-picker{
        float: right;
    }
    .el-input,.el-select{
        float: left;
        /*border: 1px red solid;*/
        width: 550px;
        /*height: 100px;*/
    }

    .avatar-uploader .el-upload {
        border: 1px dashed #d9d9d9;
        border-radius: 6px;
        cursor: pointer;
        position: relative;
        overflow: hidden;
    }
    .avatar-uploader .el-upload:hover {
        border-color: #409EFF;
    }
    .avatar-uploader-icon {
        font-size: 28px;
        color: #E6A23C;
        width: 130px;
        height: 130px;
        line-height: 130px;
        text-align: center;
    }
    .headerSize{
        font-size: 16px;
        width: 130px;
    }
    .avatar {
        width: 130px;
        height: 130px;
        display: block;
    }

</style>